import axios from 'axios';
import { ElMessage } from 'element-plus';
// store modal
import { useModalStore } from '@/pinia/modules/modal';
// user
import { useUserStore } from '@/pinia/modules/user.js';
import { getProxy } from '@/utils/helper.js';

const statusCode = {
  504: '',
};

const fetch = axios.create({
  baseURL: getProxy(),
  timeout: 15000,
});

// http request 拦截器
fetch.interceptors.request.use(
  (config) => {
    // 加了单个会失效
    // config.headers['Content-Type'] = 'application/json';
    config.headers['uniidtoken'] = localStorage.getItem('uni_id_token');

    const userStore = useUserStore();
    config.headers['miniuserid'] = userStore?.userInfo?.miniData?._id;

    return config;
  },
  (error) => {
    return error;
  },
);

// http response 拦截器
fetch.interceptors.response.use(
  (response) => {
    console.log(response, 'response');

    if (response.data.code != undefined && response.data.code != 0 && !response.config.isToast) {
      ElMessage.error(response.data.message);
    }

    return response.data;
  },
  (error) => {
    console.log(error, 'error');

    if (error.response?.data?.code == '10001') {
      localStorage.removeItem('uni_id_token');
      localStorage.removeItem('uni_id_token_expired');
      const modalStore = useModalStore();
      modalStore.openModal('login-expired-popup');
    }

    if (error.response?.data?.message) {
      ElMessage.error(error.response?.data?.message);
    } else {
      ElMessage('请求出错了');
    }
    return error;
  },
);

export default fetch;
